package de.bk.timecalc.console;

import static de.bk.timecalc.i18n.I18nKeys.*;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import de.bk.timecalc.core.TimerDirection;
import de.bk.timecalc.i18n.StringFactory;

/**
 * Reads the config properties file.
 * 
 * @author Bastian Krol
 * @version $Revision: 2947 $ $Date: 2008-10-10 14:14:41 +0200 (Fr, 10 Okt 2008)
 *          $ $Author: krol $
 */
public class ConsolePropertiesReader
{

  /**
   * File name of properties file
   */
  public static final String PROPERTIES_FILENAME = "/timecalc.properties";

  private static final String PROPERTY_NAME_LOCALE = "locale";
  private static final String CG_LEVELTIMERDIRECTION = "cg_leveltimerdirection";

  private String localeString;
  private TimerDirection timerDirection = TimerDirection.UP;

  /**
   * Reads the properties file <code>PROPERTIES_FILENAME</code>
   * 
   * @throws FileNotFoundException
   *           if properties file is not found
   */
  public void readProperties() throws FileNotFoundException
  {
    URL urlProperties = ConsolePropertiesReader.class
        .getResource(PROPERTIES_FILENAME);
    if (urlProperties == null)
    {
      throw new FileNotFoundException(this.createMessageFileNotFound());
    }
    InputStream propertiesInputStream;
    try
    {
      propertiesInputStream = urlProperties.openStream();
    }
    catch (IOException e)
    {
      throw new RuntimeException(this.createMessageFileCouldNotBeRead(), e);
    }
    if (propertiesInputStream == null)
    {
      throw new RuntimeException(this.createMessageFileCouldNotBeRead());
    }
    Properties properties = new Properties();
    try
    {
      properties.load(propertiesInputStream);
    }
    catch (IOException e)
    {
      throw new RuntimeException(this.createMessageFileCouldNotBeRead(), e);
    }

    this.localeString = (String) properties.getProperty(PROPERTY_NAME_LOCALE);
    String cg_leveltimerdirection = (String) properties
        .getProperty(CG_LEVELTIMERDIRECTION);
    if (cg_leveltimerdirection != null)
    {
      if (cg_leveltimerdirection.trim().equals("0"))
      {
        this.timerDirection = TimerDirection.UP;
      }
    }
  }

  private String createMessageFileNotFound()
  {
    return StringFactory.getInstance().format(FILE_NOT_FOUND,
        PROPERTIES_FILENAME);
  }

  private String createMessageFileCouldNotBeRead()
  {
    return StringFactory.getInstance().format(FILE_COULD_NOT_BE_READ,
        PROPERTIES_FILENAME);
  }

  public String getLocaleString()
  {
    return this.localeString;
  }

  public TimerDirection getTimerDirection()
  {
    return this.timerDirection;
  }
}
